<!--
 * @Description: 
 * @Version: 1.0
 * @Autor: gaoluo
 * @Date: 2021-10-30 10:41:32
 * @LastEditors: gaoluo
 * @LastEditTime: 2021-12-05 20:19:25
 * @FilePath: /nhw/src/views/Assignment/SubmitProcess.vue
-->
<template>
  <Layout
    :title="operation.oprName"
    class="submit-process-container"
    rightText="确认"
    @click-right="beforSubmit"
  >
    <div class="process-wrap">
      <header class="title">{{ currentNodeName }}</header>
      <CellGroup inset>
        <Field
          v-model="comment"
          label="意见"
          placeholder="请填写处理意见"
          type="textarea"
        />
      </CellGroup>

      <CellGroup inset v-for="(info, index) in infos" :key="index">
        <Cell :title="info.nextNodeName">
          <template #right-icon v-if="info.nextNodeType != 'end'">
            <Icon
              name="add-o"
              class="add-icon"
              @click="choosePeo(info.nextNodeId)"
            />
          </template>
        </Cell>
        <CheckboxGroup v-model="nextNodes[index].handleUsers">
          <Checkbox
            icon-size="18px"
            checked-color="#E16712"
            :name="item.userId"
            v-for="(item, index) in info.nextUsers"
            :key="'box' + index"
            :disabled="item.disabled ? false : !info.allowCancelDefaultPro"
            >{{ item.userName }}</Checkbox
          >
        </CheckboxGroup>
      </CellGroup>

      <CellGroup inset v-if="notify">
        <Cell title="知会">
          <template #right-icon>
            <Icon name="add-o" class="add-icon" @click="choosePeo('notify')" />
          </template>
        </Cell>
        <CheckboxGroup v-model="nextNodes[nextNodes.length - 1].handleUsers">
          <Checkbox
            icon-size="18px"
            checked-color="#E16712"
            :name="item.userId"
            v-for="(item, index) in notifyUsers"
            :key="'notify' + index"
            :disabled="item.disabled ? false : !allowCancelDefaultProNotify"
            >{{ item.userName }}</Checkbox
          >
        </CheckboxGroup>
      </CellGroup>

      <!-- 随手拍 取消 -->
      <CellGroup
        inset
        v-if="
          moduleId == 'rskmgProblemClap' && $route.params.data.oprIdx === 239
        "
      >
        <Cell class="heard" title="说明" :border="false" />
        <Field
          label="重复工单号"
          placeholder="请填写重复工单号"
          v-model="reWorkOrder"
        />
        <Field
          label="说明"
          placeholder="请填写说明"
          v-model="cancelDes"
          type="textarea"
          autosize
        />
        <UploadImage @ongetimage="handleGetPic" />
      </CellGroup>
      <!-- 随手拍 取消 -->
      <!-- 随手拍 任务分配 -->
      <CellGroup
        inset
        v-if="
          moduleId == 'rskmgProblemClap' && $route.params.data.oprIdx === 219
        "
      >
        <Cell class="heard" title="任务分配" :border="false" />
        <Cell
          title="整改时间"
          :value="responsibleTime || '请选择整改时间'"
          is-link
          @click="showstart = true"
        >
        </Cell>
      </CellGroup>
      <!-- 随手拍 任务分配 -->
      <!-- 随手拍 隐患整改 -->
      <CellGroup
        inset
        v-if="
          moduleId == 'rskmgProblemClap' && $route.params.data.oprIdx === 237
        "
      >
        <Cell class="heard" title="隐患整改" :border="false" />
        <Cell
          title="完成情况"
          :value="finishState[this.finishStateIndex].name"
          is-link
          @click="showFinishState = true"
        >
        </Cell>
        <Field
          label="整改措施"
          placeholder="请输入整改措施"
          v-model="measure"
          type="textarea"
          autosize
          input-align="right"
        />
        <UploadImage @ongetimage="handleGetPic" />
      </CellGroup>
      <!-- 随手拍 隐患整改 -->

      <!-- 专项督办 完成工作-->
      <CellGroup
        inset
        v-if="
          moduleId == 'rskmgSpecialSupervison' &&
          $route.params.data.oprName === '已完成'
        "
      >
        <Cell class="heard" title="任务答复" :border="false" />
        <Field
          label="答复信息"
          placeholder="请输入答复信息"
          v-model="correctiveText"
          type="textarea"
          autosize
          input-align="right"
        />
        <UploadImage @ongetimage="handleGetPic" />
      </CellGroup>
      <!-- 专项督办 完成工作-->
      <CellGroup
        inset
        v-if="
          moduleId == 'rskmgSpecialSupervison' &&
          $route.params.data.oprName === '延期'
        "
      >
        <Cell class="heard" title="延期信息" :border="false" />
        <Cell
          title="延期至"
          :value="correctiveTime || '请选择延期日期'"
          is-link
          @click="showstart = true"
        >
        </Cell>
        <Field
          label="延期理由"
          placeholder="请输入延期理由"
          v-model="correctiveText"
          type="textarea"
          autosize
          input-align="right"
        />
      </CellGroup>
      <!-- 专项督办 验收通过-->
      <!-- <CellGroup inset v-if="moduleId == 'rskmgSpecialSupervison'">
        <Cell class="heard" title="隐患整改" :border="false" />
        <Field
          label="验收评价"
          placeholder="请输入验收评价"
          v-model="measure"
          type="textarea"
          autosize
          input-align="right"
        />
      </CellGroup> -->
      <!-- 专项督办 延期审核 验收通过-->
    </div>
    <Popup
      get-container="body"
      close-on-popstate
      v-model="show"
      position="right"
      :style="{ height: '100%', width: '89%' }"
      @close="closePopup"
    >
      <MySearch
        @search="onSearch"
        mark="base-date"
        actionText="关闭"
        @cancel="handleCancel"
      />
      <div class="list-wrap">
        <CheckboxGroup v-model="empListChecked" v-if="empList.length > 0">
          <Checkbox
            icon-size="18px"
            checked-color="#E16712"
            :name="item.empId"
            v-for="item in empList"
            :key="item.empId"
            >{{ item.postName }} <i style="color: #e16712">-</i>
            {{ item.empName }}</Checkbox
          >
        </CheckboxGroup>
        <!-- 通用错误 -->
        <Empty
          image="error"
          description="无数据"
          v-show="empList.length <= 0"
        />
      </div>
      <!-- 底部按钮 start-->
      <div class="btn-wrap">
        <Button
          text="取消"
          color="#CACDD1"
          plain
          hairline
          @click.stop="reset"
        />
        <Button
          v-if="empList.length > 0"
          text="确认"
          color="#E16712"
          plain
          hairline
          @click.stop="confirm"
        />
      </div>
      <!-- 底部按钮 end -->
    </Popup>
    <!-- 时间 picker start-->
    <Popup
      close-on-popstate
      get-container="body"
      v-model="showstart"
      position="bottom"
      :style="{ height: '42%', width: '100vw' }"
    >
      <DatetimePicker
        v-model="startDate"
        type="datehour"
        title="选择时间"
        :min-date="minDate"
        :max-date="maxDate"
        item-height="1rem"
        @confirm="closeDatePicker"
        @cancel="closeDatePicker"
      />
    </Popup>
    <!-- 时间 picker end-->
    <!-- showFinishState picker start-->
    <Popup
      close-on-popstate
      get-container="body"
      v-model="showFinishState"
      position="bottom"
      :style="{ height: '42%', width: '100vw' }"
    >
      <Picker
        show-toolbar
        :columns="finishState"
        value-key="name"
        @confirm="getFinishState"
        @cancel="closeDatePicker"
      />
    </Popup>
    <!-- showFinishState picker end-->
  </Layout>
</template>

<script>
import qs from "qs";
import axios from "axios";
import Layout from "components/Layout";
import MySearch from "components/MySearch";
import UploadImage from "components/UploadImage";
import uploadImages from "@/utils/uploadImages1.js"; //附件
import uploadImage from "@/utils/uploadImages.js"; //图片
import formateDate from "@/utils/formateDate.js";
import {
  Popup,
  Cell,
  CellGroup,
  Field,
  Button,
  Icon,
  Checkbox,
  CheckboxGroup,
  Empty,
  Uploader,
  DatetimePicker,
  Picker,
} from "vant";
export default {
  name: "SubmitProcess",
  components: {
    Layout,
    MySearch,
    UploadImage,
    Popup,
    Cell,
    CellGroup,
    Field,
    Button,
    Icon,
    Checkbox,
    CheckboxGroup,
    Empty,
    Uploader,
    DatetimePicker,
    Picker,
  },
  data() {
    return {
      show: false,
      flag: "",
      token: "",
      userId: "",
      currentNodeId: "",
      currentNodeName: "",
      allowCancelDefaultProNotify: true,
      notifyUsers: [],
      infos: [],
      nextNodes: [],
      comment: "",
      notify: "",
      notifyIds: [],
      empList: [],
      empListChecked: [],
      empSelected: [],
      showstart: false,
      startDate: null,
      curDate: new Date(),
      // 随手拍 取消
      reWorkOrder: "", //重复工单号
      cancelDes: "", //取消说明
      fileList: [],
      //随手拍 任务分配
      responsibleTime: null,
      //随手拍  隐患整改
      showFinishState: false,
      measure: "",
      finishState: [
        { name: "请选择完成情况", disabled: true },
        { name: "按期完成", state: 1 },
        { name: "预期完成", state: 2 },
        { name: "未完成", state: 3 },
        { name: "无法完成", state: 4 },
      ],
      //完成情况
      finishStateIndex: 0,
      // 专项督办 提交
      correctiveText: "", //整改措施
      correctiveTime: null,
    };
  },
  watch: {
    startDate(nValue) {
      console.log(nValue);
      this.responsibleTime = formateDate(nValue);
      this.correctiveTime = formateDate(nValue);
    },
  },
  computed: {
    moduleId() {
      // rskmgProblemClap 随手拍
      // rskmgSpecialSupervison 专项督办
      return this.$route.params.moduleId;
    },
    modelId() {
      return this.$route.params.modelId;
    },
    pkValue() {
      return this.$route.params.pkValue;
    },
    operation() {
      return this.$route.params.data;
    },
    minDate() {
      return new Date(
        this.curDate.getFullYear() - 1,
        this.curDate.getMonth(),
        this.curDate.getDate()
      );
    },
    maxDate() {
      return new Date(
        this.curDate.getFullYear() + 2,
        this.curDate.getMonth(),
        this.curDate.getDate()
      );
    },
  },
  created() {
    this.token = window.localStorage.getItem("access_token");
    this.userId = JSON.parse(window.localStorage.getItem("userInfo")).userId;
    this.$toast.loading("加载中...");
    this.getWorkFlowProcessInfo({
      moduleId: this.moduleId,
      pkValue: this.pkValue,
      wfId: this.modelId,
      oprIdx: this.operation.oprIdx,
    }).then((res) => {
      this.$toast.clear();
      ({
        notify: this.notify,
        currentNodeId: this.currentNodeId,
        infos: this.infos,
        currentNodeName: this.currentNodeName,
        allowCancelDefaultProNotify: this.allowCancelDefaultProNotify,
        notifyUsers: this.notifyUsers,
        notifyIds: this.notifyIds,
      } = res);

      this.infos.forEach((item, index) => {
        this.nextNodes.push({
          nextNodeId: item.nextNodeId,
          handleUsers: [],
        });
        item.nextUsers.forEach((nextuser, i) => {
          this.nextNodes[index].handleUsers[i] = nextuser.userId;
        });
      });
      //添加知会
      if (this.notify) {
        const handleUsers = this.notifyUsers.map((item) => {
          return item.userId;
        });
        this.nextNodes.push({
          nextNodeId: "notify",
          notifyNodeId: this.notifyIds[0],
          handleUsers,
        });
      }
    });

    this.getEmpListData().then((data) => {
      this.empList = data.rows;
    });
  },
  mounted() {},

  methods: {
    closeDatePicker() {
      this.showstart = false;
      this.showFinishState = false;
    },
    handleGetPic(files) {
      console.log(files);
      this.fileList = files;
    },
    getFinishState(value, index) {
      this.finishStateIndex = index;
      this.showFinishState = false;
    },
    rskmgProblemClapSave(data) {
      data = qs.stringify(data);
      axios
        .post("/nhw/rskmg/rskmgProblemClap/save.ajax", data, {
          headers: {
            access_token: this.token,
          },
        })
        .then((res) => {
          if (res.data.state === 0) {
            this.submitData();
          } else {
            this.$toast(res.data.msgInfo);
          }
        });
    },
    rskmgSpecialSupervisonSave(data) {
      data = qs.stringify(data);
      axios
        .post("/nhw/rskmg/rskmgSpecialSupervison/saveDelayInfos.ajax", data, {
          headers: {
            access_token: this.token,
          },
        })
        .then((res) => {
          if (res.data.state === 0) {
            this.submitData();
          } else {
            this.$toast(res.data.msgInfo);
          }
        });
    },

    async beforSubmit() {
      //随手拍 存在疑问
      if (
        this.moduleId == "rskmgProblemClap" &&
        this.$route.params.data.oprIdx === 239
      ) {
        if (this.reWorkOrder || this.cancelDes || this.fileList.length > 0) {
          //必须填一项
          if (this.fileList.length > 0) {
            //有图片
            this.$toast.loading("图片上传中");
            const pic = await uploadImages(this.fileList);
            this.rskmgProblemClapSave({
              pkValue: this.pkValue,
              repeatId: this.reWorkOrder,
              remarkX: this.cancelDes,
              picX: pic.join(","),
            });
          } else {
            //无图片
            this.rskmgProblemClapSave({
              pkValue: this.pkValue,
              repeatId: this.reWorkOrder,
              remarkX: this.cancelDes,
            });
          }
        } else {
          this.$toast("说明中至少填一项");
        }
      }
      //随手拍 认领
      else if (
        this.moduleId == "rskmgProblemClap" &&
        this.$route.params.data.oprIdx === 219
      ) {
        if (this.startDate) {
          this.rskmgProblemClapSave({
            pkValue: this.pkValue,
            resolveEndTime: this.responsibleTime,
          });
        } else {
          this.$toast("请选择整改时间");
        }
      }
      //随手拍 提交
      else if (
        this.moduleId == "rskmgProblemClap" &&
        this.$route.params.data.oprIdx === 237
      ) {
        if (this.finishStateIndex === 4) {
          this.$toast.fail("请至PC端填写一事一档");
        } else {
          if (
            this.finishStateIndex >= 1 &&
            this.measure &&
            this.fileList.length > 0
          ) {
            //有图片
            this.$toast.loading("图片上传中");
            const pic = await uploadImages(this.fileList);
            this.rskmgProblemClapSave({
              pkValue: this.pkValue,
              rpcFinishType: this.finishState[this.finishStateIndex].state,
              rpcFinishContent: this.measure,
              rpcFinishPic: pic.join(","),
            });
          } else {
            this.$toast("请完整填写隐患整改所有数据");
          }
        }
      }
      // 专项督办
      else if (
        this.moduleId == "rskmgSpecialSupervison" &&
        this.$route.params.data.oprName === "延期"
      ) {
        if (this.startDate && this.correctiveText) {
          this.rskmgSpecialSupervisonSave({
            id: this.pkValue,
            delayTo: this.correctiveTime,
            delayReason: this.correctiveText,
          });
        } else {
          this.$toast("请填写延迟信息");
        }
      }
      // 完成工作
      else if (
        this.moduleId == "rskmgSpecialSupervison" &&
        this.$route.params.data.oprName === "已完成"
      ) {
        if (this.correctiveText && this.fileList.length > 0) {
          this.$toast.loading("图片上传中");
          const pic = await uploadImage(this.fileList);
          const data = qs.stringify({
            id: this.pkValue,
            rssTaskResponse: this.correctiveText,
            pic: pic.join(","),
          });
          axios
            .post(
              "/nhw/rskmg/rskmgSpecialSupervison/saveDoneInfos.ajax",
              data,
              {
                headers: {
                  access_token: this.token,
                },
              }
            )
            .then((res) => {
              if (res.data.state === 0) {
                this.submitData();
              } else {
                this.$toast(res.data.msgInfo);
              }
            });
        } else {
          this.$toast("请填写任务答复信息");
        }
      }
      //常规流程
      else {
        this.submitData();
      }
    },
    submitData() {
      const comment = this.comment || "<未填写>";
      const nextNodes =
        this.nextNodes[this.nextNodes.length - 1].handleUsers.length > 0
          ? this.nextNodes
          : this.nextNodes.slice(0, -1);
      if (nextNodes.length <= 0) {
        this.$toast("没有后续处理节点，无法提交流程！");
        return;
      }
      const nextNodeInfos = {
        moduleId: this.moduleId,
        workflowId: this.modelId,
        modelId: this.modelId,
        pkValue: this.pkValue,
        oprNo: this.operation.oprIdx,
        currentNodeId: this.currentNodeId, //  "currentNodeId": "node_22",
        opinion: comment, // 意见
        urgentFlag: "N", //加急 N Y
        nextNodes,
      };
      this.submitWorkflow(nextNodeInfos);
    },
    confirm() {
      //确认选择的人员
      let index = this.infos.findIndex((item) => {
        return item.nextNodeId == this.flag;
      });

      const data = this.empList.filter((item) => {
        return this.empListChecked.includes(item.empId);
      });

      this.empSelected = data.map((item) => {
        return {
          userId: item.empId,
          userName: item.empName,
          disabled: true,
        };
      });

      if (this.flag == "notify") {
        index = this.nextNodes.length - 1;
        this.notifyUsers.push(...this.empSelected);
      } else {
        this.infos[index].nextUsers.push(...this.empSelected);
      }
      this.nextNodes[index].handleUsers.push(...this.empListChecked);
      this.flag = "";
      this.show = false;
    },
    reset() {
      this.show = false;
    },
    closePopup() {
      this.empListChecked = [];
    },
    choosePeo(value) {
      console.log(value);
      this.flag = value;
      this.show = true;
    },
    onSearch({ key }) {
      this.getEmpListData(key).then((data) => {
        this.empList = data.rows;
      });
    },
    handleCancel() {
      this.reset();
    },
    //提交
    async submitWorkflow(data) {
      this.$toast.loading("提交中...");
      data = qs.stringify({
        access_token: this.token,
        nextNodeInfos: JSON.stringify(data),
        userId: this.userId,
      });
      const res = await axios.post(
        "/nhw/workflow/api/submitWorkflow.ajax",
        data,
        {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        }
      );
      this.$toast(res.data.msgInfo);
      if (res.data.state == 0) {
        setTimeout(() => {
          this.$router.replace({ name: "Assignment" });
        }, 0);
      }
    },
    //获取流程信息
    async getWorkFlowProcessInfo({ moduleId, pkValue, wfId, oprIdx } = {}) {
      const res = await axios.get(
        "/nhw/workflow/api/getWorkFlowProcessInfo.ajax",
        {
          params: {
            access_token: this.token,
            userId: this.userId,
            moduleId,
            pkValue,
            wfId,
            oprIdx,
          },
        }
      );

      if (res.status == 200) {
        const { data } = res;
        return data;
      } else {
        this.$toast.fail("网络异常！");
        throw "network error";
      }
    },
    //获取人员列表
    async getEmpListData(searchParams) {
      const res = await axios.get("/nhw/workflow/api/getEmpList.ajax", {
        params: {
          access_token: this.token,
          searchParams,
        },
      });
      if (res.status == 200) {
        const { data } = res;
        return data;
      } else {
        this.$toast.fail("网络异常！");
        throw "network error";
      }
    },
  },
};
</script>

<style lang="less" scoped>
@import url("~style/var.less");
@import url("~style/mixin.less");
.submit-process-container {
  .process-wrap {
    width: 100%;
    // background: #fff;
    header {
      text-align: center;
      line-height: 2;
      background: @primary;
      color: #fff;
    }
    .van-checkbox {
      padding: 20px 30px;
    }
  }
  .van-cell-group {
    margin-top: 10px;
  }
  .add-icon {
    color: @primary;
    font-size: 44px;
    line-height: inherit;
  }
  .van-checkbox {
    font-size: 28px;
  }
  .heard {
    text-align: center;
    color: #fff;
    background: @primary;
  }
}

.van-popup {
  .van-checkbox {
    font-size: 28px;
    margin: 20px;
    padding: 10px;
    box-shadow: 0 0 3px 0 rgba(0, 0, 0, 0.1);
    &[aria-checked="true"] {
      box-shadow: 0 0 3px 0 rgba(240, 111, 6, 1);
    }
  }
  .list-wrap {
    height: calc(100vh - 188px);
    overflow: scroll;
    box-sizing: border-box;
  }
  .btn-wrap {
    width: 100%;
    margin-top: 10px;
    .flex();
    .van-button {
      margin: 0 20px;
      padding: 0 40px;
      height: 0.8rem;
    }
  }
}
</style>